package com.example.spring.bean.load03scope;

import com.example.spring.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * 测试单例，spring默认情况下，bean就是单实例
 * <p> 跟随容器一起创建的，每次取出来的实例都是同一个
 * <p>
 */
//@Configuration
public class SingletonTest {

    @Bean
    @Scope("singleton")
    User singleUser() {
        User user = new User();
        user.setId(11);
        user.setName("singleUser");
        return user;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SingletonTest.class);
        Object singleUser1 = context.getBean("singleUser");

        //User{id=11, name='singleUser'}
        System.out.println(singleUser1);

        Object singleUser2 = context.getBean("singleUser");

        //true; 虽然分别取了两次对象，但是这两个对象都是同一个对象
        System.out.println(singleUser1 == singleUser2);

        User bean = context.getBean(User.class);
        //true ,也是同一个对象
        System.out.println(singleUser1 == bean);

        context.close();
    }
}
